<template>
    <div class="Box">
      <!-- 顶部搜索 -->
      <div class="SearchBox flex-LAR">
        <el-input v-model="SearchKeyWord.searchValue" placeholder="请输入搜索内容" class="input-with-select">
          <template #prepend>
            <el-select v-model="SearchKeyWord.selectKey" style="width: 6.25rem">
              <el-option label="职位名称" value="position" />
              <el-option label="团队名称" value="team_name" />
            </el-select>
          </template>
          <template #append>
            <el-button class="searchBtn" :icon="Search" />
          </template>
        </el-input>
      </div>
      <!-- 表格 -->
      <div class="TableBox">
        <cy-table class="Table" row-key="recruitment_id" :data="tableData" :columns="ruleTable.columns" :loading="loading" />
      </div>
      <!-- 分页 -->
      <div class="PageBox">
        <el-pagination :hide-on-single-page="true" v-model:current-page="page.currentPage" v-model:page-size="page.pageSize"
          v-model:total="page.total" />
      </div>
  
      <!-- 新增/编辑弹窗 -->
      <el-dialog v-model="dialogVisible" :title="dialogTitle" width="70%">
        <el-form :model="form" label-width="120px" :rules="rules" ref="formRef">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="职位名称" prop="position">
                <el-input v-model="form.position" placeholder="请输入职位名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属团队" prop="team_id">
                <el-select v-model="form.team_id" placeholder="请选择所属团队">
                  <el-option v-for="team in teamList" :key="team.team_id" :label="team.team_name" :value="team.team_id" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="招聘人数" prop="vacancies">
                <el-input-number v-model="form.vacancies" :min="1" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="截止日期" prop="deadline">
                <el-date-picker v-model="form.deadline" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" />
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="工作性质" prop="job_type">
                <el-select v-model="form.job_type" placeholder="请选择工作性质">
                  <el-option v-for="item in jobTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态" prop="status">
                <el-select v-model="form.status" placeholder="请选择状态">
                  <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-form-item label="职位描述" prop="description">
            <el-input v-model="form.description" type="textarea" :rows="4" placeholder="请输入职位描述" />
          </el-form-item>
  
          <el-form-item label="职位要求" prop="requirements">
            <el-input v-model="form.requirements" type="textarea" :rows="4" placeholder="请输入职位要求" />
          </el-form-item>
  
          <el-form-item label="福利待遇" prop="benefits">
            <el-input v-model="form.benefits" type="textarea" :rows="3" placeholder="请输入福利待遇" />
          </el-form-item>
  
          <el-form-item label="联系方式" prop="contact">
            <el-input v-model="form.contact" placeholder="请输入联系方式" />
          </el-form-item>
        </el-form>
  
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script lang="tsx" setup>
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Search } from "@element-plus/icons-vue";
  import CyTable from "@/components/table";
  
  const page = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
  });
  
  const SearchKeyWord = reactive({
    selectKey: "position",
    searchValue: "",
  });
  
  const tableData = ref([
    {
      recruitment_id: 1,
      position: '应急救援队员',
      team_id: 1,
      team_name: '应急救援队',
      vacancies: 5,
      deadline: '2023-06-30',
      job_type: 'volunteer',
      description: '参与社区应急救援工作，协助处理突发事件',
      requirements: '18-50周岁，身体健康，有责任心',
      benefits: '提供培训，颁发志愿者证书',
      contact: '王主任 13800138000',
      status: 'open',
      created_at: '2023-05-01',
      applicants: 12
    },
    {
      recruitment_id: 2,
      position: '医疗志愿者',
      team_id: 2,
      team_name: '医疗应急队',
      vacancies: 3,
      deadline: '2023-07-15',
      job_type: 'volunteer',
      description: '参与社区医疗应急服务，提供基本医疗帮助',
      requirements: '有医疗背景或急救证书者优先',
      benefits: '提供专业培训，积累实践经验',
      contact: '李医生 13900139000',
      status: 'open',
      created_at: '2023-05-10',
      applicants: 8
    },
    {
      recruitment_id: 3,
      position: '心理咨询师',
      team_id: 3,
      team_name: '心理援助队',
      vacancies: 2,
      deadline: '2023-05-31',
      job_type: 'part_time',
      description: '为社区居民提供心理支持和危机干预',
      requirements: '心理学相关专业，有心理咨询师证书',
      benefits: '按小时计酬，提供督导支持',
      contact: '张老师 13700137000',
      status: 'closed',
      created_at: '2023-04-15',
      applicants: 5
    },
    {
      recruitment_id: 4,
      position: '后勤保障人员',
      team_id: 4,
      team_name: '后勤保障队',
      vacancies: 4,
      deadline: '2023-08-20',
      job_type: 'volunteer',
      description: '负责应急物资管理和后勤保障工作',
      requirements: '有责任心，能吃苦耐劳',
      benefits: '提供必要的工作保障和培训',
      contact: '赵主管 13600136000',
      status: 'open',
      created_at: '2023-06-01',
      applicants: 6
    },
    {
      recruitment_id: 5,
      position: 'IT技术支持',
      team_id: 5,
      team_name: '技术保障队',
      vacancies: 1,
      deadline: '2023-06-15',
      job_type: 'part_time',
      description: '维护社区应急通讯系统和技术设备',
      requirements: '熟悉网络和通讯设备维护',
      benefits: '按项目付费，工作时间灵活',
      contact: '陈工 13500135000',
      status: 'closed',
      created_at: '2023-05-05',
      applicants: 3
    }
  ]);
  
  const teamList = ref([
    { team_id: 1, team_name: '应急救援队' },
    { team_id: 2, team_name: '医疗应急队' },
    { team_id: 3, team_name: '心理援助队' },
    { team_id: 4, team_name: '后勤保障队' },
    { team_id: 5, team_name: '技术保障队' }
  ]);
  
  const ruleTable = reactive({
    columns: [
      { prop: "recruitment_id", label: "招聘ID" },
      { prop: "position", label: "职位名称" },
      { prop: "team_name", label: "所属团队" },
      { prop: "vacancies", label: "招聘人数" },
      { prop: "deadline", label: "截止日期" },
      {
        prop: "job_type", label: "工作性质",
        render: ({ row }) => (
          <el-tag type={getJobTypeTag(row.job_type)}>
            {getJobTypeName(row.job_type)}
          </el-tag>
        ),
      },
      {
        prop: "status", label: "状态",
        render: ({ row }) => (
          <el-tag type={getStatusTag(row.status)}>
            {getStatusName(row.status)}
          </el-tag>
        ),
      },
      { prop: "applicants", label: "申请人数" },
      {
        label: "操作",
        align: "center",
        render: ({ row }) => (
          <div>
            <el-button>查看</el-button>
            <el-button type="primary">申请</el-button>
          </div>
        ),
      },
    ],
  });
  
  const dialogVisible = ref(false);
  const dialogTitle = ref('');
  const formRef = ref(null);
  
  const form = reactive({
    recruitment_id: '',
    position: '',
    team_id: '',
    vacancies: 1,
    deadline: '',
    job_type: '',
    description: '',
    requirements: '',
    benefits: '',
    contact: '',
    status: 'open'
  });
  
  const rules = reactive({
    position: [{ required: true, message: '请输入职位名称', trigger: 'blur' }],
    team_id: [{ required: true, message: '请选择所属团队', trigger: 'change' }],
    vacancies: [{ required: true, message: '请输入招聘人数', trigger: 'blur' }],
    deadline: [{ required: true, message: '请选择截止日期', trigger: 'change' }],
    job_type: [{ required: true, message: '请选择工作性质', trigger: 'change' }],
    status: [{ required: true, message: '请选择状态', trigger: 'change' }],
    description: [{ required: true, message: '请输入职位描述', trigger: 'blur' }],
    requirements: [{ required: true, message: '请输入职位要求', trigger: 'blur' }],
  });
  
  const jobTypeOptions = ref([
    { value: 'full_time', label: '全职' },
    { value: 'part_time', label: '兼职' },
    { value: 'volunteer', label: '志愿者' },
    { value: 'internship', label: '实习' }
  ]);
  
  const statusOptions = ref([
    { value: 'draft', label: '草稿' },
    { value: 'open', label: '招聘中' },
    { value: 'closed', label: '已结束' }
  ]);
  
  const getJobTypeName = (type) => {
    const item = jobTypeOptions.value.find(item => item.value === type);
    return item ? item.label : '未知';
  };
  
  const getJobTypeTag = (type) => {
    const map = {
      full_time: 'success',
      part_time: 'primary',
      volunteer: 'info',
      internship: 'warning'
    };
    return map[type] || '';
  };
  
  const getStatusName = (status) => {
    const item = statusOptions.value.find(item => item.value === status);
    return item ? item.label : '未知';
  };
  
  const getStatusTag = (status) => {
    const map = {
      draft: '',
      open: 'success',
      closed: 'danger'
    };
    return map[status] || '';
  };
  
  const handleAdd = () => {
    dialogTitle.value = '发布新招聘';
    formRef.value?.resetFields();
    dialogVisible.value = true;
  };
  
  const submitForm = () => {
    formRef.value.validate((valid) => {
      if (valid) {
        if (form.recruitment_id) {
          const index = tableData.value.findIndex(item => item.recruitment_id === form.recruitment_id);
          if (index !== -1) {
            tableData.value[index] = { 
              ...form,
              team_name: getTeamName(form.team_id),
              applicants: tableData.value[index].applicants || 0
            };
            ElMessage.success('编辑成功');
          }
        } else {
          form.recruitment_id = tableData.value.length + 1;
          form.created_at = new Date().toISOString().split('T')[0];
          form.applicants = 0;
          tableData.value.push({ 
            ...form,
            team_name: getTeamName(form.team_id)
          });
          ElMessage.success('发布成功');
        }
        dialogVisible.value = false;
      } else {
        ElMessage.error('表单验证失败');
      }
    });
  };
  
  const getTeamName = (id) => {
    const team = teamList.value.find(team => team.team_id === id);
    return team ? team.team_name : '未知';
  };
  </script>
  
  <style scoped lang="scss">
  .Box {
    position: relative;
  
    .SearchBox {
      width: 100%;
      height: 60px;
      background-color: #fff;
      border-bottom: 1px solid #eee;
  
      .el-input {
        width: 350px;
        margin-left: 0.5rem;
      }
  
      .searchBtn {
        color: rgb(15, 153, 245);
      }
  
      .addBtn {
        margin-right: 1rem;
      }
    }
  
    .PageBox {
      background-color: #fff;
      padding-left: 30%;
      margin: 1rem;
    }
  
    .TableBox {
      .Table {
        width: 100%;
        min-height: 25rem;
        border-top: 1px solid #eee;
      }
    }
  
    .EditForm {
      :deep(.el-form-item__content) {
        display: flex;
        justify-content: center;
        align-content: center;
      }
    }
  }
  </style>